<?php

namespace App\Models;

use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Enrollment extends Model
{
	use SoftDeletes;
	protected $fillable = ['creator_id', 'place_id', 'census_id', 'employee_id', 'type', 'name', 'email', 'mobile', 'nation', 'gender', 'politics', 'marriage', 'id_type', 'id_number', 'deposit_bank', 'bank_number', 'education', 'graduation', 'profession', 'current_address', 'residence_address', 'emergency_name', 'emergency_mobile', 'status', 'hired_at', 'birthed_at'];

	protected $casts = [
        'hired_at'  => 'datetime:Y-m-d',
		'birthed_at'  => 'datetime:Y-m-d'
	];

	public static $statusMap = [
		1	=> '待审核',
		2	=> '审核中',
		3	=> '已驳回',
        4   => '生效中',
		5	=> '已失效',
	];

    public static $eduMap = [
        1   =>  '小学',
        2   =>  '初中',
        3   =>  '高中',
        4   =>  '中专',
        5   =>  '大专',
        6   =>  '本科',
    ];

    public static $politicsMap = [
        1 => '中国共产党党员',
        2 => '中国共产党预备党员',
        3 => '中国共产主义青年团团员',
        4 => '中国国民党革命委员会会员',
        5 => '中国民主同盟盟员',
        6 => '中国民主建国会会员',
        7 => '中国民主促进会会员',
        8 => '中国农工民主党党员',
        9 => '中国致公党党员',
        10 => '九三学社社员',
        11 => '台湾民主自治同盟盟员',
        12 => '无党派民主人士',
        13 => '群众'
    ];

    public static $genderMap = [
        1   =>  '男',
        2   =>  '女',
    ];
    // 选填项
    public static $marriageMap = [
        0   =>  '未知',
        1   =>  '未婚',
        2   =>  '已婚',
        3   =>  '丧偶',
        4   =>  '离婚',
    ];

    public static $idTypeMap = [
        1   =>  '身份证',
    ];

    public static $typeMap = [
        1   =>  '全职',
        2   =>  '兼职',
        3   =>  '实习',
        4   =>  '外包',
        5   =>  '劳务',
        6   =>  '顾问',
        7   =>  '返聘',
    ];

    public static $attachMap = [
        1   =>  '身份证',
        2   =>  '银行卡',
        3   =>  '毕业证',
        4   =>  '入职登记',
        5   =>  '免冠照片',
        6   =>  '体检报告',
        7   =>  '离职证明',
        8   =>  '保密协议',
        9   =>  '竟业协议',
    ];

    public static $nationMap = [
        1   =>  '汉族',
        2   =>  '壮族',
        3   =>  '满族',
        4   =>  '回族',
        5   =>  '苗族',
        6   =>  '维吾尔族',
        7   =>  '土家族',
        8   =>  '彝族',
        9   =>  '蒙古族',
        10  =>  '藏族',
        11  =>  '布依族',
        12  =>  '侗族',
        13  =>  '瑶族',
        14  =>  '朝鲜族',
        15  =>  '白族',
        16  =>  '哈尼族',
        17  =>  '哈萨克族',
        18  =>  '黎族',
        19  =>  '傣族',
        20  =>  '畲族',
        21  =>  '傈僳族',
        22  =>  '仡佬族',
        23  =>  '东乡族',
        24  =>  '高山族',
        25  =>  '拉祜族',
        26  =>  '水族',
        27  =>  '佤族',
        28  =>  '纳西族',
        29  =>  '羌族',
        30  =>  '土族',
        31  =>  '仫佬族',
        32  =>  '锡伯族',
        33  =>  '柯尔克孜族',
        34  =>  '达斡尔族',
        35  =>  '景颇族',
        36  =>  '毛南族',
        37  =>  '撒拉族',
        38  =>  '布朗族',
        39  =>  '塔吉克族',
        40  =>  '阿昌族',
        41  =>  '普米族',
        42  =>  '鄂温克族',
        43  =>  '怒族',
        44  =>  '京族',
        45  =>  '基诺族',
        46  =>  '德昂族',
        47  =>  '保安族',
        48  =>  '俄罗斯族',
        49  =>  '裕固族',
        50  =>  '乌孜别克族',
        51  =>  '门巴族',
        52  =>  '鄂伦春族',
        53  =>  '独龙族',
        54  =>  '塔塔尔族',
        55  =>  '赫哲族',
        56  =>  '珞巴族'
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($m) {
            if (!$m->no) {
                $m->no = static::findAvailableNo();
                if (!$m->no) return false;
            }
        });
        static::updated(function ($m) {
            if ($m->getOriginal('status') != $m->status && $m->status === 4) {
                if ($employee = Employee::find($m->employee_id)) {
                    $employee->name = $m->name;
                    $employee->mobile = $m->mobile;
                    $employee->hired_at = $m->hired_at;
                    $employee->positive_at = null;
                    $employee->separated_at = null;
                    $employee->save();
                }
            }
        });
    }

	public function place()
	{
		return $this->belongsTo(Region::class, 'place_id');
	}

    public function census()
    {
        return $this->belongsTo(Region::class, 'census_id');
    }

    public function creator()
    {
        return $this->belongsTo(Employee::class);
    }

	public function employee()
	{
		return $this->belongsTo(Employee::class);
	}

    public function departure()
    {
        return $this->hasOne(Departure::class)->latest();
    }

    public function Departures()
    {
        return $this->hasMany(Departure::class);
    }

    public function attachments()
    {
        return $this->morphMany(ObjectStorage::class, 'common')->orderByDesc('created_at');
    }

    public function scopeWhichKeyword($q, $k)
    {
        if (!$k) return $q;
        return $q->where(self::qualifyColumn('no'), 'like', "%{$k}%")
                ->orWhere(self::qualifyColumn('name'), 'like', "%{$k}%")
                ->orWhere(self::qualifyColumn('email'), 'like', "%{$k}%")
                ->orWhere(self::qualifyColumn('id_number'), 'like', "%{$k}%")
                ->orWhere(self::qualifyColumn('deposit_bank'), 'like', "%{$k}%")
                ->orWhere(self::qualifyColumn('bank_number'), 'like', "%{$k}%")
                ->orWhere(self::qualifyColumn('profession'), 'like', "%{$k}%")
                ->orWhere(self::qualifyColumn('current_address'), 'like', "%{$k}%")
                ->orWhere(self::qualifyColumn('emergency_name'), 'like', "%{$k}%")
                ->orWhere(self::qualifyColumn('emergency_mobile'), 'like', "%{$k}%");
    }

    public function scopeWhichEmployee($q, $s, $u = 0)
    {
        return $q->when($s, function ($q, $s) use($u) {
            if (!is_array($s)) {
                $s = [$s];
            }
            $q->whereIn(self::qualifyColumn('employee_id'), $s);
            if ($u) {
                foreach ($s as $i) {
                    DB::table('search_weights')->updateOrInsert(['user_id' => $u, 'employee_id' => $i]);
                }
                DB::table('search_weights')->where('user_id', $u)->whereIn('employee_id', $s)->increment('total');
            }
        });
    }

    public function scopeWhichPlace($q, $s)
    {
        return $q->when($s, function ($q, $s) {
            if (!is_array($s)) {
                $s = [$s];
            }
            $q->whereIn(self::qualifyColumn('place_id'), $s);
        });
    }

    public function scopeWhichCensus($q, $s)
    {
        return $q->when($s, function ($q, $s) {
            if (!is_array($s)) {
                $s = [$s];
            }
            $q->whereIn(self::qualifyColumn('census_id'), $s);
        });
    }

    public function scopeWhichIdType($q, $s)
    {
        return $q->when($s, function ($q, $s) {
            if (!is_array($s)) {
                $s = [$s];
            }
            $q->whereIn(self::qualifyColumn('id_type'), $s);
        });
    }

    public function scopeWhichNation($q, $s)
    {
        return $q->when($s, function ($q, $s) {
            if (!is_array($s)) {
                $s = [$s];
            }
            $q->whereIn(self::qualifyColumn('nation'), $s);
        });
    }

    public function scopeWhichPolitics($q, $s)
    {
        return $q->when($s, function ($q, $s) {
            if (!is_array($s)) {
                $s = [$s];
            }
            $q->whereIn(self::qualifyColumn('politics'), $s);
        });
    }

    public function scopeWhichEducation($q, $s)
    {
        return $q->when($s, function ($q, $s) {
            if (!is_array($s)) {
                $s = [$s];
            }
            $q->whereIn(self::qualifyColumn('education'), $s);
        });
    }

    public function scopeWhichStatus($q, $s)
    {
        return $q->when($s, function ($q, $s) {
            if (!is_array($s)) {
                $s = [$s];
            }
            $q->whereIn(self::qualifyColumn('status'), $s);
        });
    }

    public function scopeWhichAt($c, $a, $d)
    {
        $at = "{$a}_at";
        if (! in_array($at, ["hired_at", "birthed_at", "created_at"])) return $c;
        $field = self::qualifyColumn($at);
        if (! is_array($d)) return $c->orderByDesc($field);
        if ($d[0]) $c->where($field, '>=', $d[0]);
        if ($d[1]) $c->where($field, '<=', $d[1]);
    }

    public static function findAvailableNo()
    {
        $prefix = 'E'.date('YmdHis');
        for ($i = 0; $i < 4; $i++) {
            $no = $prefix.str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT);
            if (!static::query()->whereNo($no)->exists()) return $no;
            usleep(100);
        }
        \Log::warning(sprintf('find contract no failed'));
        return false;
    }
}
